import {Component, OnInit} from '@angular/core';
import {adSystemApiUrl, AliyunOssOutputUrl} from '../../../config/api';
import {HttpService} from '../../lib/service/http.service'
import {Router, ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-news-list',
  templateUrl: 'news-list.component.html',
  styleUrls: ['news-list.component.scss']
})
export class NewsListComponent implements OnInit {

  allInfo: any;//所有信息
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  categoryID = 0;  // 资讯类型
  totalItems: number;
  currentPage: number;
  itemsPerPage = 12;
  categoryName = '所有资讯';
  classifyList = [];  // 所有分类

  constructor(
    private httpService: HttpService,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.route.queryParams.subscribe(
      res => {
        this.categoryID = +res.categoryId||0;
      }
    );
    this.getClassifyList();
    this.getAllArtical(1, this.itemsPerPage, this.categoryID);
  }

  // 获取所有最新资讯列表
  getAllArtical(page: number, pageSize: number, categoryID?: number) {
    let url;
    if(!!categoryID && categoryID != 0){
      url = `${adSystemApiUrl}/v1/fddata/posts/list?page=${page}&pageSize=${pageSize}&categoryID=${categoryID}`;
    }else{
      url = `${adSystemApiUrl}/v1/fddata/posts/list?page=${page}&pageSize=${pageSize}`;
    }
    return this.httpService.httpGetAuth(url)
      .subscribe(
        data => {
          this.currentPage = data.data.current_page;
          this.totalItems = data.data.total;
          this.allInfo = data.data.data;
        }
      );
  }

  // 获取分类列表
  getClassifyList() {
    const url = `${adSystemApiUrl}/v1/fddata/category/list`;
    return this.httpService.httpGetAuth(url)
      .subscribe(
        data => {
          this.classifyList = data.data;
        }
      )
  }

  changeType(data: any) {
    this.categoryID = data.id;
    this.categoryName = data.name;
    this.getAllArtical(1, this.itemsPerPage, this.categoryID);
  }

  // 跳转到新闻详情页
  turnNewsDetail(data: any) {
    this.router.navigate(['/home/news-detail/' + data.id], {queryParams: {categoryId: data.category_id}});
  }

  pageChanged(event: any): void {
    window.scrollTo(0,0);
    this.getAllArtical(event.page, event.itemsPerPage, this.categoryID);
  }
}
